<?php
namespace app\index\controller;
use app\model\Service as ServiceModel;

use think\Db;


class Service extends Base
{   
    protected $noCheckToken = ['index','read','recommend','calendarDetail'];

    public function calendarDetail(){
        $map_params = [
           ['key'=>'category_uuid','type'=>'='],
           ['key'=>'color','type'=>'='],
        ];
        $map = getSearchParam($map_params);
        if (isSearchParam('keyword_search')) {
            $map[] = ['name','like','%'.input('keyword_search').'%'];
        }
        $map[] = ['status','=',1];
        $map[] = ['is_delete','=',0];

        $month = input('month',date('Y-m'));
        $start_time = $month.'-01';
        $end_time = date('Y-m-d',strtotime('+1 month',strtotime($start_time)) - 1);

        $page_param = ['page'=>input('page_index',1),'list_rows'=>input('page_size',10)];
        $list = Db::name('lesson_time')->field('date,service_uuid')->where([
            ['date','between',[$start_time,$end_time]],
            Db::raw('service_uuid is not null')
        ])->order('date asc')->group('date,service_uuid')->paginate($page_param)->toarray();

        $course_uuids = [];
        $times = [];
        foreach ($list['data'] as $k => $vo) {
            if ( empty($course_uuids[$vo['date']]) ) {
                $course_uuids[$vo['date']] = [];
            }
            if (!empty($vo['course_uuid'])) {
                $course_uuids[$vo['date']]['courses'][] = $vo['course_uuid'];
                $times['courses'][$vo['course_uuid']] = $vo['time'];
            }elseif (!empty($vo['service_uuid'])){
                $course_uuids[$vo['date']]['services'][] = $vo['service_uuid'];
                $times['services'][$vo['service_uuid']] = $vo['time'];
            }else{
                $course_uuids[$vo['date']]['activitys'][] = $vo['activity_uuid'];
                $times['activitys'][$vo['activity_uuid']] = $vo['time'];
            }
        }

        // $activitys = Db::name('activity')->field('activity_date,uuid')->where([
        //     ['activity_date','between',[$start_time,$end_time]],
        // ])->select();
        // foreach ($activitys as $k => $vo) {
        //     $date = date('Y-m-d',strtotime($vo['activity_date']));
        //     $course_uuids[$date]['activitys'][] = $vo['uuid'];
        // }


        $list['data'] = [];
        foreach ($course_uuids as $date => $uuids) {
            // $course_uuid = array_unique($course_uuid);
            $data = ['date'=>$date,'service'=>[]];
            if (!empty($uuids['courses'])) {
                $course_uuid = array_unique($uuids['courses']);
                $map2 = $map;
                $map2[] = ['uuid','in',$course_uuid];
                if (isSearchParam('teacher_uuid')) {
                    $map2[] = ['teacher_uuid','=',input('teacher_uuid')];
                }
                if (isSearchParam('tags')) {
                    $map2[] = ['tags','like',input('tags')];
                }
                $courses = Db::name('course')->where($map2)->order('create_time asc')->select();
                foreach ($courses as $k => $course) {
                    $courses[$k]['teacher'] = Db::name('admin')->field('uuid,truename,mobile,create_time,email,teacher_level,image,content,description')->where('uuid',$course['teacher_uuid'])->find();
                }
                $data['course'] = $courses;
                foreach ($data['course'] as $ck => $cv) {
                    $data['course'][$ck]['time'] = $times['courses'][$cv['uuid']];
                }
            }
            if (!empty($uuids['services'])) {
                $services_uuid = array_unique($uuids['services']);
                $map2 = $map;
                $map2[] = ['uuid','in',$services_uuid];
                if (isSearchParam('teacher_uuid')) {
                    $map2[] = ['teacher_uuid','=',input('teacher_uuid')];
                }
                if (isSearchParam('tags')) {
                    $map2[] = ['tags','like',input('tags')];
                }
                $services = Db::name('service')->where($map2)->order('create_time asc')->select();
                foreach ($services as $k => $service) {
                    $services[$k]['teacher'] = Db::name('admin')->field('uuid,truename,mobile,create_time,email,teacher_level,image,content,description')->where('uuid',$service['teacher_uuid'])->find();
                }
                $data['service'] = $services;
                foreach ($data['service'] as $ck => $cv) {
                    $data['service'][$ck]['time'] = $times['services'][$cv['uuid']];
                }
            }
            if (!empty($uuids['activitys'])) {
                $activity_uuid = array_unique($uuids['activitys']);
                $map2 = $map;
                $map2[] = ['uuid','in',$activity_uuid];
                $data['activity'] = Db::name('activity')->field('uuid,name,color')->where($map2)->order('create_time asc')->limit(4)->select();
                foreach ($data['activity'] as $ck => $cv) {
                    $data['activity'][$ck]['time'] = $times['activitys'][$cv['uuid']];
                }
            }
            if (!empty($data['course']) || !empty($data['service']) || !empty($data['activity'])) {
                $list['data'][] = $data;
            }
            

            // $list[] = [
            //     'date'=>$date,
            //     'course'=>Db::name('course')->field('uuid,name,color')->where([
            //         ['status','=',1],
            //         ['uuid','in',$uuids['courses']]
            //     ])->order('create_time asc')->limit(4)->select(),
            //     'service'=>Db::name('service')->field('uuid,name,color')->where([
            //         ['status','=',1],
            //         ['uuid','in',$uuids['services']]
            //     ])->order('create_time asc')->limit(4)->select(),
            // ];
        }

        return apiResult('2000','获取成功',$list);
    }

    // 列表
    public function index(){
        $map_params = [
           ['key'=>'category_uuid','type'=>'='],
           ['key'=>'teacher_uuid','type'=>'='],
           ['key'=>'is_top','type'=>'='],
        ];
        $map = getSearchParam($map_params);
        if (isSearchParam('keyword_search')) {
            $map[] = ['name','like','%'.input('keyword_search').'%'];
        }
        if (isSearchParam('start_time')) {
            $map[] = ['create_time','>=',input('start_time')];
        }
        if (isSearchParam('end_time')) {
            $map[] = ['create_time','<=',input('end_time')];
        }
        if (input('is_collect',0) == 1) {
            $user_uuid = $this->login_user['uuid'];
            $uuids = Db::name('collect')->where([
                ['user_uuid','=',$user_uuid],
                ['type','=',1]
            ])->column('target_uuid');
            $map[] = ['uuid','in',$uuids];
        }
        $map[] = ['status','=',1];
        $map[] = ['is_delete','=',0];

        $model = new ServiceModel();
        $page_param = ['page'=>input('page_index',1),'list_rows'=>input('page_size',10)];
        $list = $model->field('content,status',true)->where($map)->order('create_time desc')->paginate($page_param)->toarray();
        foreach ($list['data'] as $k => $vo) {
            $list['data'][$k]['tags'] = myExplode($vo['tags']);

            $list['data'][$k]['category'] = Db::name('category')->field('name')->where('uuid',$vo['category_uuid'])->find();
            $list['data'][$k]['teacher'] = Db::name('admin')->field('uuid,truename,mobile,create_time,email,teacher_level,image,content,description')->where('uuid',$vo['teacher_uuid'])->find();
        }

        return apiResult('2000','获取成功',$list);
    }

    // 详情
    public function read($uuid){
        $user_uuid = $this->login_user['uuid'];

        $model = new ServiceModel();
        $data = $model->where('uuid',$uuid)->find();
        if (!empty($data)) {
            $data['tags'] = myExplode($data['tags']);
            $data['images'] = myExplode($data['images']);

            $data['classroom'] = Db::name('classroom')->where('uuid',$data['classroom_uuid'])->find();
            $data['category'] = Db::name('category')->field('name')->where('uuid',$data['category_uuid'])->find();
            $data['teacher'] = Db::name('admin')->field('uuid,truename,mobile,create_time,email,teacher_level,image,content,description')->where('uuid',$data['teacher_uuid'])->find();
            $data['lesson_time'] = json_decode($data['lesson_time'],true);

            $data['is_collect'] = Db::name('collect')->where([
                ['user_uuid','=',$user_uuid],
                ['target_uuid','=',$data['uuid']],
                ['type','=',1]
            ])->count() > 0 ? 1 : 0;

            $djxx_field = Db::name('djxx_field')->where('uuid',$data['djxx_field_uuid'])->find();
            $djxx_field['fields'] = json_decode($djxx_field['fields'],true);
            $data['djxx_field'] = $djxx_field;
        }

        return apiResult('2000','获取成功',$data);
    }

    // 推荐
    public function recommend(){
        $map_params = [
           ['key'=>'category_uuid','type'=>'='],
        ];
        $map = getSearchParam($map_params);
        if (isSearchParam('keyword_search')) {
            $map[] = ['name','like','%'.input('keyword_search').'%'];
        }
        if (isSearchParam('uuid')) {
            $map[] = ['uuid','<>',input('uuid')];
        }
        $map[] = ['status','=',1];

        $model = new ServiceModel();
        $list = $model->field('content,status',true)->where($map)->orderRaw('rand()')->limit(10)->select()->toarray();
        foreach ($list as $k => $vo) {
            $list[$k]['tags'] = myExplode($vo['tags']);

            $list[$k]['category'] = Db::name('category')->field('name')->where('uuid',$vo['category_uuid'])->find();
            $list[$k]['teacher'] = Db::name('admin')->field('uuid,truename,mobile,create_time,email,teacher_level,image,content,description')->where('uuid',$vo['teacher_uuid'])->find();
        }

        return apiResult('2000','获取成功',$list);
    }

    // 收藏
    public function collect($uuid){
        $user_uuid = $this->login_user['uuid'];
        $map = [
            ['user_uuid','=',$user_uuid],
            ['target_uuid','=',$uuid],
            ['type','=',1]
        ];
        if (Db::name('collect')->where($map)->count() > 0) {
            Db::name('collect')->where($map)->delete();
            return apiResult('2000','取消收藏成功',['type'=>0]);
        }else{
            Db::name('collect')->insert([
                'user_uuid'=>$user_uuid,
                'target_uuid'=>$uuid,
                'type'=>1,
                'create_time'=>date('Y-m-d H:i:s')
            ]);
            return apiResult('2000','收藏成功',['type'=>1]);
        }
    }

    // 新增
    public function save(){
        $param = file_get_contents('php://input');
        $param = json_decode($param,true);

        $fields = [
            'must'=>['name','cover','price','stock','content','valid_time','category_uuid','color','type','teacher_uuid'],
            'nomust'=>['images','tags','status','before_time','after_time','is_fuke','pre_course_uuid','package_course_uuid','description']
        ];

        $save_data = paramFilter($param,$fields);
        if (!empty($save_data['error_msg'])) {
            return apiResult('5000',$save_data['error_msg']);
        }

        $model = new ServiceModel();
        // 启动事务 
        Db::startTrans();
        try{
            $save_data['uuid'] = uuidCreate();
            $save_data['create_time'] = date('Y-m-d H:i:s');
            if ( !$model->save($save_data) ) {
                throw new \Exception("保存失败");
            }
           
            // 更新成功 提交事务
            Db::commit();

            return apiResult('2000','提交成功',$save_data['uuid']);
        } catch (\Exception $e) {
            // 更新失败 回滚事务
            Db::rollback();
            return apiResult('5000',$e->getMessage());
        }
    }

    // 更新
    public function update(){
        $param = file_get_contents('php://input');
        $param = json_decode($param,true);

        if ( empty($param['uuid']) ) {
            exception('uuid不能为空',400);
        }

        $fields = [
            'nomust'=>['name','cover','price','stock','content','valid_time','category_uuid','color','type','images','tags','status','before_time','after_time','is_fuke','pre_course_uuid','package_course_uuid','teacher_uuid','description']
        ];
        $save_data = paramFilter($param,$fields);
        if (!empty($save_data['error_msg'])) {
            return apiResult('5000',$save_data['error_msg']);
        }
        if (empty($save_data)) {
            return apiResult('5000','无任何修改');
        }

        $model = new ServiceModel();
        // 启动事务 
        Db::startTrans();
        try{
            if ( $model->where('uuid',$param['uuid'])->update($save_data) === false ) {
                throw new \Exception("保存失败");
            }
            // 同步更新课节时间
            if ( isset($save_data['before_time']) || isset($save_data['after_time']) ) {
                $lesson_times = Db::name('lesson_time')->where('course_uuid',$param['uuid'])->select();
                if ( isset($save_data['before_time']) ) {
                    foreach ($lesson_times as $k => $vo) {
                        $time_a = explode('-',$vo['time']);    
                        $start_time = strtotime($vo['date'].' '.$time_a[0]) - $save_data['before_time'] * 60;
                        Db::name('lesson_time')->where('id',$vo['id'])->update(['start_time'=>$start_time]);
                    }
                }
                if ( isset($save_data['after_time']) ) {
                    foreach ($lesson_times as $k => $vo) {
                        $time_a = explode('-',$vo['time']);    
                        $end_time = strtotime($vo['date'].' '.$time_a[1]) + $save_data['after_time'] * 60;
                        Db::name('lesson_time')->where('id',$vo['id'])->update(['end_time'=>$end_time]);
                    }
                }
            }
            // 更新成功 提交事务
            Db::commit();

            return apiResult('2000','更新成功');
        } catch (\Exception $e) {
            // 更新失败 回滚事务
            Db::rollback();
            return apiResult('5000',$e->getMessage());
        }
    }

    // 删除
    public function delete($uuid){
        $model = new ServiceModel();
        Db::startTrans();
        try{
            if ( !$model->where('uuid',$uuid)->delete() ) {
                throw new \Exception("删除失败");
            }

            Db::name('lesson')->where('course_uuid',$uuid)->delete();
            Db::name('lesson_time')->where('course_uuid',$uuid)->delete();
            // 更新成功 提交事务
            Db::commit();
            return apiResult('2000','删除成功');
        } catch (\Exception $e) {
            // 更新失败 回滚事务
            Db::rollback();
            return apiResult('5000',$e->getMessage());
        }
    }
   


}
